<template>
  <el-row class="user-info-form form-deal-alarm" type="flex" justify="center" v-loading="loading">
    <el-col>
      <el-form label-width="130px" :model="handleForm" :rules="handleFormRules" ref="handleForm" @submit.native.prevent>
        <div v-if="oldInfo.length==1" class="row-img">
          <el-image
            v-if="picUrl"
            :src="picUrl"
            fit="contain"
            @click="onPreview(oldInfo[0],1)"
            style="width: 192px; height: 108px;"
          ></el-image>
          <div class="desc">{{oldInfo[0].selfDesc}}</div>
        </div>
        <el-form-item label="选择操作方法：" v-if="handleForm.status == -1">
          <el-radio-group :disabled="handleTypeDisabled" v-model="dialoghandlerStatus">
            <el-radio label="2">领取，但是稍后处理</el-radio>
            <el-radio label="1">现在就处理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理类型：" prop="handleTypeId" v-if="dialoghandlerStatus == 1">
          <el-select filterable @change="handleSelectChange" v-model="handleForm.handleTypeId" placeholder="请选择处理类型">
            <el-option
              v-for="item in handleTypeOptions"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            ></el-option>
          </el-select>
          <div>
            <el-tag
              class="tag-handle-type"
              :effect="handleForm.handleTypeId==item.type?'dark':'plain'"
              v-for="(item) in topHandleTypeList"
              :key="item.type"
              @click="handleForm.handleTypeId=item.type;handleSelectChange(item.type)"
            >{{item.typeName}}</el-tag>
          </div>
        </el-form-item>

        <!-- 增加梯控表单 -->
        <el-form-item label="是否禁用梯控：" v-if="handleElevatorVisible && dialoghandlerStatus == 1">
          <template v-if="elevatorStatusInfo.status!=5">
            <el-radio v-model="handleForm.disableElevator" label="0">不禁用</el-radio>
            <el-radio-group v-model="handleForm.time">
              <el-radio label="600">禁用10分钟</el-radio>
              <el-radio label="3600">禁用1小时</el-radio>
              <el-radio label="86400">禁用1天</el-radio>
              <el-radio label="-1">永久禁用</el-radio>
            </el-radio-group>
          </template>
          <div v-else>因为梯控离线，所以无法操作</div>
          <div style="color:red;margin-top:8px;line-height:16px;">
            <span
              v-if="(elevatorStatusInfo.status==3&&elevatorStatusInfo.disableStartTimeStr&&elevatorStatusInfo.disableEndTimeStr)"
            >当前梯控禁用时间：{{elevatorStatusInfo.disableStartTimeStr}} ~ {{elevatorStatusInfo.disableEndTimeStr}}</span>
            <span
              v-else-if="(elevatorStatusInfo.status==3&&(!elevatorStatusInfo.disableStartTimeStr||!elevatorStatusInfo.disableEndTimeStr))"
            >当前梯控状态：永久禁用</span>
            <span v-else>
              当前梯控状态：{{getElevatorControlStatus(elevatorStatusInfo.status)}}
              <span
                v-if="elevatorStatusInfo.status==5"
              >，请先将梯控设备恢复正常</span>
            </span>
          </div>
        </el-form-item>

        <el-form-item label="添加备注：" prop="remark" v-if="dialoghandlerStatus == 1">
          <el-input v-model="handleForm.remark" type="textarea" placeholder="请输入火灾描述" clearable></el-input>
        </el-form-item>
        <el-form-item label="现场图片/视频：" v-if="dialoghandlerStatus == 1">
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="true"
            ref="upload"
            list-type="picture-card"
            :data="qiniuData"
            :on-success="handleAvatarSuccess"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload"
            :file-list="qiniuData.fileList"
            accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png, video/mp4, video/3gp, video/mpeg, video/mavip4, video/flv, video/mov"
          >
            <template v-slot:file="scope" class="videoImage">
              <div style="width:100%;height:100%;">
                <img
                  v-if="'mp4,3gp,mpeg,mavip4,mov,flv'.includes(scope.file.raw.name.split('.')[scope.file.raw.name.split('.').length - 1].toLowerCase())"
                  style="width:100%;height:100%;"
                  :src="require('@/assets/images/video/video-detail.png')"
                />
                <img v-else :src="scope.file.url" alt="图片" style="width:100%;height:100%;" />
                <span class="el-upload-list__item-actions" style="width:100%;height:100%;">
                  <span
                    class="el-upload-list__item-preview"
                    :data-type="scope.file.raw.type"
                    :data-imgpreview="scope.file.url"
                    @click="$imgPreview"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span class="el-upload-list__item-delete" @click="deleteVideo(scope.file)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
                <label class="el-upload-list__item-status-label">
                  <i class="el-icon-upload-success el-icon-check"></i>
                  <i class="el-icon-close"></i>
                  <i class="el-icon-close-tip"></i>
                </label>
              </div>
            </template>
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="选择预案：" v-show="handleForm.handleTypeId == 2 && dialoghandlerStatus == 1">
          <el-select filterable @change="planSelectChange" v-model="handleForm.planId" placeholder="请选择预案">
            <el-option v-for="item in planTypeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="预案流程：" v-show="handleForm.handleTypeId == 2">
              <el-input :disabled="true" v-model="flowContent" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="小组分工：" v-show="handleForm.handleTypeId == 2">
              <el-input :disabled="true" v-model="taskContent" type="textarea"></el-input>
        </el-form-item>-->
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button @click="closeFun">取消</el-button>
          <el-button type="primary" @click="submitHandle('handleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <image-viewer ref="ImageViewer" :origin-list="originList"></image-viewer>
  </el-row>
</template>
<script>
import util from '@/utils/util'
import { qnToken } from '@/api/api'
import { getDictByCode } from '@/api/dic'
import {
  selectEmergencyPlanInfo,
  selectEmergencyPlanDetail,
  getFcfAndElecontro,
} from '@/api/plan'
import { handleFireRecord, getTopAlarmHandlerType } from '@/api/alarm'
import ImageViewer from '@/components/TransAiPic/ImageViewer'

export default {
  name: 'DealWithPolice',
  components: { ImageViewer },
  props: {
    oldInfo: {
      required: true,
    },
    closeFun: {
      required: true,
    },
    formatPicUrl: {
      type: Function,
      default: function () {},
    },
    dealType: {
      type: [String],
      default: '1',
    },
  },
  data() {
    return {
      defaultImg: this.GLOBAL.defaultImg,
      loading: false,
      orgIdsArr: [],
      recordsInfosStr: [],
      qiniuData: {
        //上传图片携带的参数
        token: '',
        key: '',
        fileList: [],
      },
      handleTypeOptions: [], // 处理类型下拉框选项
      planTypeOptions: [], // 应急预案下拉框选项
      dialoghandlerStatus: '1',
      handleForm: {
        handleTypeId: '1',
        remark: '',
        status: '-1',
        fireTypeId: 0,
        operator: this.$store.state.userinfo.accountName,
        remarkVoice: '',
        picUrl: '',
        planId: '',
        isOpenPlan: 0,
        recordsInfosStr: '',
        time: '', // 梯控禁用时长
        disableElevator: '',
      },
      handleFormRules: {
        handleTypeId: [
          { required: true, message: '请选择处理类型', trigger: 'change' },
        ],
      },
      taskContent: '', //预案相关
      flowContent: '', //预案相关
      handleTypeDisabled: false, // 处理方式是否禁用
      handleElevatorVisible: false, // 梯控是否展示
      elevatorStatusInfo: {},
      topHandleTypeList: [],
      originList: [],
      picUrl: '',
    }
  },
  watch: {
    handleElevatorVisible: {
      handler(val, oldVal) {
        if (!val) this.$set(this.handleForm, 'disableElevator', '-1')
        if (val) this.$set(this.handleForm, 'disableElevator', '0')
      },
      deep: true,
    },
    'handleForm.disableElevator': {
      handler(val, oldVal) {
        if (val === '0') this.$set(this.handleForm, 'time', '')
      },
      deep: true,
    },
    'handleForm.time': {
      handler(val, oldVal) {
        if (val) this.$set(this.handleForm, 'disableElevator', '1')
      },
      deep: true,
    },
  },
  created() {
    this.dialoghandlerStatus = this.dealType.toString()
    if (this.oldInfo[0].picturesUrls) {
      this.picUrl = this.formatPicUrl(this.oldInfo[0].picturesUrls)
    } else {
      this.picUrl = this.oldInfo[0].detailPic
        ? JSON.parse(this.oldInfo[0].detailPic).icon || this.defaultImg
        : this.defaultImg
    }

    this.originHandleForm = {}
    if (!this.handleElevatorVisible) {
      this.$set(this.handleForm, 'disableElevator', '-1')
    }
    this.getToken() // 获取token
    //绑定处理类型下拉框
    getDictByCode({ code: 60 }).then((data) => {
      this.handleTypeOptions = data.data.dictValueObj
      this.getTopAlarmHandlerType()
    })
    // 多个业主单位拼接, 多条记录拼接
    // let fcFacilitiesIdArr = []
    for (let i = 0, len = this.oldInfo.length; i < len; i++) {
      this.orgIdsArr.push(this.oldInfo[i].organizationId)
      this.recordsInfosStr.push({
        id: this.oldInfo[i].id,
        createTime: this.oldInfo[i].createTime,
        fcfId: this.oldInfo[i].fcFacilitiesId,
      })
      // 已经领取过了，只能选择立即处理
      if (this.oldInfo[i].handlerStatus === 2) this.handleTypeDisabled = true
    }
    // 是否展示梯控选项 113 115  王超需求 : 批量处理 如果全部是梯控->展示 如果有一个不是梯控->不展示 ; 单个处理->展示
    let isShowElevator =
      this.oldInfo.length == 1 &&
      this.oldInfo.every((val) => {
        return val.fireSTypes === '113' || val.fireSTypes === '115'
      })
    if (isShowElevator) {
      this.getFcfAndElecontro()
    }
  },
  methods: {
    onPreview(row, index) {
      if (this.oldInfo[0].picturesUrls) {
        let arr = [
          {
            pic: this.oldInfo[0].picturesUrls + '',
            resultRegion: this.oldInfo[0].picAlarmRegion + '',
          },
        ]
        if (this.oldInfo[0].aiExtInfoList) {
          this.oldInfo[0].aiExtInfoList.forEach((n) => {
            arr.push({
              pic: n.imageInfo.pic,
              resultRegion: JSON.stringify(n),
            })
          })
        }
        this.originList = arr
      } else {
        this.originList = [
          {
            pic: this.picUrl + '',
            resultRegion: '',
          },
        ]
      }
      this.$nextTick(() => {
        this.$refs.ImageViewer.switchPic(0)
      })
    },
    // 获取梯控状态名称
    getElevatorControlStatus(key) {
      let mapObj = {
        2: '触发',
        4: '正常',
        5: '离线',
      }
      return mapObj[key] || ''
    },
    // 常用处理类型
    getTopAlarmHandlerType() {
      getTopAlarmHandlerType().then((res) => {
        if (res && res.status == 200) {
          this.topHandleTypeList = res.data
          if (res.data.length > 0) {
            this.handleForm.handleTypeId = res.data[0].type
            this.handleSelectChange(res.data[0].type)
          }
        }
      })
    },
    //处理
    getFcfAndElecontro() {
      this.loading = true
      getFcfAndElecontro({
        fcFacilitiesId: this.oldInfo[0].fcFacilitiesId,
      }).then((res) => {
        if (res.status === 200) {
          if (res.data) {
            let data = res.data
            // data={
            //   status:2,
            //   // disableStartTimeStr:'2021-01-01 09:00:00',
            //   // disableEndTimeStr:'2021-01-01 10:00:00',
            // }
            this.handleElevatorVisible = true
            this.elevatorStatusInfo = data
            // 禁用状态且没有截止时间为永久禁用
            if (data.status == 3) {
              // 禁用状态
              this.handleForm.time = ''
              this.handleForm.disableElevator = '1'
              if (!data.disableEndTimeStr) {
                //永久禁用
                this.handleForm.time = '-1'
              }
            } else if (data.status == 4 || data.status == 2) {
              // 正常/触发状态，默认选中不禁用
              this.handleForm.disableElevator = '0'
              this.handleForm.time = ''
            } else {
              // 不选中是否禁用梯控
              this.handleForm.disableElevator = '-1'
              this.handleForm.time = ''
            }
          } else {
            this.handleElevatorVisible = false
            this.elevatorStatusInfo = {}
          }
          // 记录梯控初始状态
          this.originHandleForm.time = this.handleForm.time.toString()
          this.originHandleForm.disableElevator =
            this.handleForm.disableElevator.toString()
          this.loading = false
        }
      })
    },
    getToken() {
      //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token = result.data
      })
    },
    // 删除视频
    deleteVideo(file) {
      let fileList = []
      this.qiniuData.fileList.forEach((item, index) => {
        if (item.uid !== file.uid) {
          fileList.push(item)
        }
      })
      this.qiniuData.fileList = fileList
    },
    beforeAvatarUpload: function (file) {
      //重命名和校验
      var isAgainUpload = false
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
      const isImage = 'png,jpg,jpeg,bmp,gif'.includes(
        file.type.split('/')[file.type.split('/').length - 1].toLowerCase()
      )
      const isVideo = 'mp4,3gp,mpeg,mavip4,mov,flv'.includes(
        file.type.split('/')[file.type.split('/').length - 1].toLowerCase()
      )
      const isLt20M = file.size / 1024 / 1024 < 20

      this.qiniuData.fileList.forEach((item) => {
        if (file.name === item.name && file.size === item.size) {
          isAgainUpload = true
          return false
        }
      })

      if (isAgainUpload) {
        this.$message.error('不能上传重复的照片或视频！')
        return false
      }

      if (!isImage && !isVideo) {
        this.$message.error('上传文件格式不正确 !')
        return false
      }

      if (isVideo) {
        // 最长30s
        return this.getVideoTimeLength(file)
      }

      if (!isLt20M && isImage) {
        this.$message.error('图片大小不能超过 20MB!')
        return false
      }
    },
    // 获取视频长度
    getVideoTimeLength(file) {
      let _this = this
      let url = URL.createObjectURL(file)
      let audioElement = new Audio(url)
      let duration // 视频时长
      return new Promise((resolve, reject) => {
        audioElement.addEventListener('loadedmetadata', function (_event) {
          duration = audioElement.duration //时长为秒，小数
          if (Math.floor(duration) > 30) {
            _this.$message.error('现场视频时长不能超过30s !')
            reject()
          } else {
            resolve()
          }
        })
      })
    },
    handleAvatarSuccess: function (res, file, fileList) {
      //上传成功
      this.qiniuData.fileList = fileList
    },
    handleError: function (res) {
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning',
      })
    },
    handleSelectChange(val) {
      let selectedText = ''
      $.each(this.handleTypeOptions, (index, obj) => {
        if (obj.dictKey == val) {
          selectedText = obj.dictValue
          return false
        }
      })
      this.handleForm.remark = selectedText
      if (val == 2) {
        //大型火情，要启动预案

        //绑定该业主单位预案下拉框
        selectEmergencyPlanInfo({
          orgIds: this.orgIdsArr.join(','),
          planName: '',
          pageSize: 100,
          pageIndex: 0,
        }).then((data) => {
          this.planTypeOptions = data.data || []
        })
      }
    },
    planSelectChange(val) {
      this.taskContent = ''
      this.flowContent = ''
      selectEmergencyPlanDetail({
        planId: val,
      }).then((data) => {
        if (data.data) {
          this.taskContent = data.data.taskContent
          this.flowContent = data.data.flowContent
        }
      })
    },
    submitHandle(formName) {
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let parames
          // console.log(that.dialoghandlerStatus);
          //稍后处理
          if (that.dialoghandlerStatus == 2) {
            parames = {
              status: that.dialoghandlerStatus,
              fireTypeId: 0,
              operator: that.$store.state.userinfo.accountName,
              isOpenPlan: 0,
              recordsInfosStr: JSON.stringify(this.recordsInfosStr),
              disableElevator: '-1',
            }
          } else {
            // 立即处理
            parames = {
              handleTypeId: that.handleForm.handleTypeId,
              remark: that.handleForm.remark,
              status: 1,
              fireTypeId: that.handleForm.fireTypeId,
              operator: that.$store.state.userinfo.accountName,
              remarkVoice: that.handleForm.remarkVoice,
              picUrl: util.ilinkArrHandle
                .getqiniuPicUrlArr(that.qiniuData.fileList)
                .toString(),
              planId: that.handleForm.planId,
              isOpenPlan: (that.handleForm.isOpenPlan =
                that.handleForm.handleTypeId == 2 ? 1 : 0),
              recordsInfosStr: JSON.stringify(this.recordsInfosStr),
              time: that.handleForm.time,
              // 禁用状态不变则传-1
              disableElevator: this.isElevatorStatusChanged()
                ? that.handleForm.disableElevator
                : '-1',
            }
          }
          // console.log(parames);
          // return;
          if (
            this.dialoghandlerStatus == 1 &&
            ['1', '2', '3'].indexOf(this.handleForm.handleTypeId) > -1
          ) {
            let one =
              this.handleTypeOptions.filter((n) => {
                return n.dictKey == this.handleForm.handleTypeId
              })[0] || {}
            this.$confirm(
              `确认处理为${one.dictValue || '真实警情'}吗?`,
              '提示',
              {
                customClass: 'msgbox-handle-alarm',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              }
            )
              .then(() => {
                this.requestSubmit(parames)
              })
              .catch(() => {})
          } else {
            this.requestSubmit(parames)
          }
        } else {
          return false
        }
      })
    },
    requestSubmit(parames) {
      this.loading = true
      handleFireRecord(parames).then((res) => {
        if (res.status === 200) {
          this.$message({
            message: '保存成功！',
            type: 'success',
          })
          this.closeFun(true)
        } else {
          this.$message({
            message: res.info,
            type: 'warning',
          })
        }
        this.loading = false
      })
    },
    isElevatorStatusChanged() {
      return (
        this.handleForm.time !== this.originHandleForm.time ||
        this.handleForm.disableElevator !==
          this.originHandleForm.disableElevator
      )
    },
  },
}
</script>

<style lang="scss">
.form-deal-alarm {
  .el-radio {
    line-height: 28px;
  }
  .tag-handle-type {
    margin: 10px 8px 0 0;
    cursor: pointer;
  }
  .row-img {
    display: flex;
    align-items: center;
    padding: 0 0 10px 20px;
    .desc {
      margin-left: 20px;
      flex: 1;
    }
  }
}
.msgbox-handle-alarm {
  .el-message-box__status {
    color: #f56c6c;
  }
}
.videoPreview {
  .videoPreview_videoDisplay {
    display: block;
    margin: 0 auto;
  }
  .container-imgpre {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
